package cn.shrek.controller;

import cn.shrek.vo.ActiverUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 */
@Controller
public class ProviderLoginController {
    /**
     * 跳转到登陆页面
     *
     */
    @GetMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    /**
     * 登陆
     */
    @PostMapping ("doLogin")
    public String doLogin(String user_name, String userpwd, HttpServletRequest request){
        //封装token
        UsernamePasswordToken token=new UsernamePasswordToken(user_name,userpwd);
        //得到主体
        Subject subject= SecurityUtils.getSubject();
        try{
            subject.login(token);
            //登陆成功
            ActiverUser activerUser= (ActiverUser) subject.getPrincipal();
            request.getSession().setAttribute("user",activerUser.getUser());
//            Cookie cookie = new Cookie("user","123");
            return "list";
        }catch (UnknownAccountException e){
            request.setAttribute("error","用户不存在");
            System.out.println(e);
        }catch (CredentialsException e){
            request.setAttribute("error","密码不正确");
            System.out.println(e);
        }catch (Exception e){
            request.setAttribute("error","用户名或密码不正确");
            System.out.println(e);
        }
        return "login";
    }

    @GetMapping("/end")
    public String go_index(
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response){
        request.getSession().removeAttribute("user");
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);//设置存活时间，“0”即马上消失
        cookie.setPath("/");
        response.addCookie(cookie);
        session.invalidate();
        return "redirect:/";
    }

}
